package com.jianjun.ktui.ui.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.savedstate.SavedState
import androidx.savedstate.savedState
import androidx.savedstate.write
import com.jianjun.ktui.defaultLocale
import com.jianjun.ktui.ui.data.UserStore
import jianjun_gradle.composeapp.generated.resources.Res
import jianjun_gradle.composeapp.generated.resources.item_right
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.ui.tooling.preview.Preview


/**
 *
 * @author source
 * {@code @date} 2025/3/27 09:30
 */
@OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
@Composable
fun ConfigScreen(
    showSnackbar: (String) -> Unit,
    uiState: SavedState,
    onQueryClicked: () -> Unit,
    rows: MutableList<MutableMap<String, Any>>
) {
    val heads = listOf(
        "参数主键", "参数名称", "参数键名", "参数键值", "系统内置", "备注", "创建时间", "操作"
    )
    var configName by remember { mutableStateOf("") }
    var configKey by remember { mutableStateOf("") }
    var configType by remember { mutableStateOf("") }
    var beginTime by remember { mutableStateOf("") }
    var endTime by remember { mutableStateOf("") }
    var configTypeDialog by remember { mutableStateOf(false) }
    var dateDialog by remember { mutableStateOf(false) }
    val dateRangePickerState = rememberDateRangePickerState()
    val dateFormatter = remember { DatePickerDefaults.dateFormatter(selectedDateSkeleton = "yyyy-MM-dd") }
    when {
        configTypeDialog -> {
            AlertDialog(
                title = { Text("请选择系统内置") },
                text = {
                    FlowRow(modifier = Modifier.padding(20.dp)) {
                        UserStore.getDict("sys_job_group").forEach {
                            Card(
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.surface,
                                ),
                                modifier = Modifier.padding(5.dp).fillMaxWidth(0.36f),
                                onClick = {
                                    configType = it["dictValue"] as String
                                    configTypeDialog = false
                                }
                            ) {
                                Text(
                                    it["dictLabel"] as String,
                                    modifier = Modifier.padding(10.dp).align(Alignment.CenterHorizontally)
                                )
                            }
                        }
                    }
                },
                confirmButton = {},
                dismissButton = {},
                onDismissRequest = {
                    configTypeDialog = false
                },
            )
        }

        dateDialog -> {
            DatePickerDialog(
                onDismissRequest = {
                    dateDialog = false
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            if (dateRangePickerState.selectedStartDateMillis == null || dateRangePickerState.selectedEndDateMillis == null) {
                                showSnackbar("请选择日期范围")
                                return@TextButton
                            }
                            beginTime = dateFormatter.formatDate(
                                dateRangePickerState.selectedStartDateMillis,
                                locale = defaultLocale()
                            )!!
                            endTime = dateFormatter.formatDate(
                                dateRangePickerState.selectedEndDateMillis,
                                locale = defaultLocale()
                            )!!
                            dateDialog = false
                        }
                    ) {
                        Text("确定")
                    }
                },
                dismissButton = {
                    TextButton(onClick = {
                        dateDialog = false
                    }) {
                        Text("取消")
                    }
                }
            ) {
                DateRangePicker(
                    state = dateRangePickerState,
                    dateFormatter = dateFormatter,
                    title = {
                        Text(
                            text = "选择日期范围"
                        )
                    },
                    headline = {
                        DateRangePickerDefaults.DateRangePickerHeadline(
                            selectedStartDateMillis = dateRangePickerState.selectedStartDateMillis,
                            selectedEndDateMillis = dateRangePickerState.selectedEndDateMillis,
                            displayMode = dateRangePickerState.displayMode,
                            dateFormatter,
                            modifier = Modifier.padding(PaddingValues(start = 64.dp, end = 12.dp, bottom = 12.dp))
                        )
                    },
                    showModeToggle = false,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(500.dp)
                        .padding(16.dp)
                )
            }
        }

    }
    Column {
        FlowRow(
            modifier = Modifier.padding(10.dp),
            horizontalArrangement = Arrangement.spacedBy(10.dp)
        ) {
            OutlinedTextField(
                value = configName,
                label = {
                    Text("参数名称")
                },
                placeholder = {
                    Text("请输入参数名称")
                },
                onValueChange = {
                    configName = it
                },
                singleLine = true
            )
            OutlinedTextField(
                value = configKey,
                label = {
                    Text("参数键名")
                },
                placeholder = {
                    Text("请输入参数键名")
                },
                onValueChange = {
                    configKey = it
                },
                singleLine = true
            )
            OutlinedTextField(
                value = UserStore.getDict("sys_yes_no").find { it["dictValue"] == configType }
                    ?.get("dictLabel") as? String ?: "",
                modifier = Modifier.clickable { configTypeDialog = true },
                label = {
                    Text("系统内置")
                },
                placeholder = {
                    Text("请选择系统内置")
                },
                leadingIcon = {
                    Icon(painterResource(Res.drawable.item_right), null)
                },
                onValueChange = {},
                enabled = false,
                singleLine = true,
                colors = OutlinedTextFieldDefaults.colors().copy(
                    disabledTextColor = OutlinedTextFieldDefaults.colors().unfocusedTextColor,
                    disabledPrefixColor = OutlinedTextFieldDefaults.colors().unfocusedPrefixColor,
                    disabledTrailingIconColor = OutlinedTextFieldDefaults.colors().unfocusedTrailingIconColor,
                    disabledLabelColor = OutlinedTextFieldDefaults.colors().unfocusedLabelColor,
                    disabledLeadingIconColor = OutlinedTextFieldDefaults.colors().unfocusedLeadingIconColor,
                    disabledContainerColor = OutlinedTextFieldDefaults.colors().unfocusedContainerColor,
                    disabledPlaceholderColor = OutlinedTextFieldDefaults.colors().unfocusedPlaceholderColor,
                    disabledSupportingTextColor = OutlinedTextFieldDefaults.colors().unfocusedSupportingTextColor,
                    disabledIndicatorColor = OutlinedTextFieldDefaults.colors().unfocusedIndicatorColor,
                )
            )
            OutlinedTextField(
                value = if (beginTime.isNotEmpty() && endTime.isNotEmpty()) "$beginTime - $endTime" else "",
                modifier = Modifier.clickable { dateDialog = true },
                label = {
                    Text("创建时间")
                },
                placeholder = {
                    Text("开始日期 - 结束日期")
                },
                leadingIcon = {
                    Icon(painterResource(Res.drawable.item_right), null)
                },
                onValueChange = {},
                enabled = false,
                singleLine = true,
                colors = OutlinedTextFieldDefaults.colors().copy(
                    disabledTextColor = OutlinedTextFieldDefaults.colors().unfocusedTextColor,
                    disabledPrefixColor = OutlinedTextFieldDefaults.colors().unfocusedPrefixColor,
                    disabledTrailingIconColor = OutlinedTextFieldDefaults.colors().unfocusedTrailingIconColor,
                    disabledLabelColor = OutlinedTextFieldDefaults.colors().unfocusedLabelColor,
                    disabledLeadingIconColor = OutlinedTextFieldDefaults.colors().unfocusedLeadingIconColor,
                    disabledContainerColor = OutlinedTextFieldDefaults.colors().unfocusedContainerColor,
                    disabledPlaceholderColor = OutlinedTextFieldDefaults.colors().unfocusedPlaceholderColor,
                    disabledSupportingTextColor = OutlinedTextFieldDefaults.colors().unfocusedSupportingTextColor,
                    disabledIndicatorColor = OutlinedTextFieldDefaults.colors().unfocusedIndicatorColor,
                )
            )
            Button(
                modifier = Modifier.align(Alignment.CenterVertically),
                onClick = {
                    uiState.write {
                        putString("configName", configName)
                        putString("configKey", configKey)
                        putString("configType", configType)
                        putString("beginTime", beginTime)
                        putString("endTime", endTime)
                    }
                    onQueryClicked()
                }
            ) {
                Icon(Icons.Filled.Search, null)
                Text("查询")
            }
            Button(
                modifier = Modifier.align(Alignment.CenterVertically),
                onClick = {
                    configName = ""
                    configKey = ""
                    configType = ""
                    beginTime = ""
                    endTime = ""
                }
            ) {
                Icon(Icons.Filled.Refresh, null)
                Text("重置")
            }
        }
        SelectionContainer {
            Column(modifier = Modifier.padding(10.dp)) {
                Row(modifier = Modifier.background(MaterialTheme.colorScheme.secondaryContainer)) {
                    heads.forEach {
                        Text(it, textAlign = TextAlign.Center, modifier = Modifier.weight(1f))
                        VerticalDivider()
                    }
                }
                HorizontalDivider()
                rows.forEach {
                    Row {
                        Text(it["configId"].toString(), textAlign = TextAlign.Center, modifier = Modifier.weight(1f))
                        VerticalDivider()
                        Text(
                            it["configName"] as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text(
                            it["configKey"] as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text(
                            it["configValue"] as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text(
                            UserStore.getDict("sys_yes_no").find
                            { d -> d["dictValue"] == it["configType"].toString() }
                                ?.get("dictLabel") as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text(
                            it["remark"] as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text(
                            it["createTime"] as? String ?: "",
                            textAlign = TextAlign.Center,
                            modifier = Modifier.weight(1f)
                        )
                        VerticalDivider()
                        Text("操作", textAlign = TextAlign.Center, modifier = Modifier.weight(1f))
                        VerticalDivider()
                    }
                    HorizontalDivider()
                }
            }
        }
    }
    //开始进入默认点击
    if (rows.isEmpty()) {
        uiState.write {
            putString("configName", configName)
            putString("configKey", configKey)
            putString("configType", configType)
            putString("beginTime", beginTime)
            putString("endTime", endTime)
        }
        onQueryClicked()
        UserStore.getDict("sys_yes_no")
    }
}

@Preview(widthDp = 700, heightDp = 500)
@Composable
fun ConfigScreenPreview() {
    ConfigScreen(
        showSnackbar = {},
        uiState = savedState(),
        onQueryClicked = {},
        rows = mutableListOf()
    )
}